<?php

namespace app\index\controller;

use app\common\builder\ZBuilder;
use app\common\controller\Apicommon;
use \app\index\model\Admin as AdminModel;
use app\index\model\Rules;
use think\helper\Hash;
use think\Validate;

/**
 * 管理员设置
 * @package app\index\controller
 */
class Admin extends Apicommon
{
    public function initialize()
    {
        //parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
        // 默认跳转模块
        if(empty(session('user_auth.uid'))){
            $this->redirect('login');
        }else{
            $this->uid = session('user_auth.uid');
        }
    }

    /**
     * 创建管理员
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->request();
            $rule = [
                'username'=>'require|unique:admin',
                'password'=>'require|length:6,18',
//                'token'=>'token',
            ];
            $field = [
                'username'=>'登录名',
                'password'=>'密码',
//                'token'=>'Token',
            ];
            $validate = new Validate($rule,[],$field);
            $check = $validate->check($param);
            $param['password'] = Hash::make($param['password']);
            $param['status'] = 1;

            if (!$check) $this->error_json($validate->getError());

            AdminModel::create($param);
            $this->success_json('创建成功');
        }
        return $this->fetch();
    }
    /**
     * 修改管理员
     * @return mixed
     */
    public function edit($id = null)
    {
        $id = $id ?: $this->request->request('id');
        if (empty($id)) die('未选择用户');

        if ($this->request->isPost()) {
            $param = $this->request->request();
            $rule = [
                'username'=>'require|unique:admin,username,'.$id,
                'password'=>'length:6,18',
//                'token'=>'token',
            ];
            $field = [
                'username'=>'登录名',
                'password'=>'密码',
//                'token'=>'Token',
            ];
            $validate = new Validate($rule,[],$field);
            $check = $validate->check($param);
            if (empty($param['password'])) {
                unset($param['password']);
            }else{
                $param['password'] = Hash::make($param['password']);
            }

            $param['status'] = 1;

            if (!$check) $this->error_json($validate->getError());

            AdminModel::update($param,['id'=>$id]);
            $this->success_json('创建成功');
        }
        $info = AdminModel::get($id);
        $this->assign('row',$info);
        return $this->fetch();
    }

    /**
     * 管理员列表
     * @param int $page 页码
     * @param int $limit 一页显示数量
     * @return mixed
     */
    public function adminList()
    {
        $admin = new AdminModel();
        $field = "
            admin.*,
            admin_role.name role_name
        ";
        $list = $admin->alias('admin')->field($field)
            ->leftJoin('admin_role','admin_role.id = admin.role')
            ->paginate(input('limit', 10), false);
        $data = $list->items();

        $this->assign('pages', $list->render());
        $this->assign('row', $data);
        $this->assign('row',$data);
        return $this->fetch();
    }

    /**
     * 个人设置
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function profile($id = null)
    {
        // 保存数据
        if ($this->request->isPost()) {
            $this->request->filter('trim');
            $data = $this->request->post();

            if (empty($data['nickname'])) {
                $this->error_json('昵称不能为空');
            }
            $data['id'] = $this->uid;

            // 如果没有填写密码，则不更新密码
            if (empty($data['password'])) {
                unset($data['password']);
            }else{
                $data['password'] = Hash::make($data['password']);
            }

            $UserModel = new AdminModel();
            if ($user = $UserModel->allowField(['nickname', 'password', 'mobile'])->update($data)) {
                $this->success_json('编辑成功');
            } else {
                $this->error_json('编辑失败');
            }
        }

        // 获取数据
        $row = AdminModel::where('id', $this->uid)->field('password', true)->find();
        $this->assign('row',$row);
        return $this->fetch();
    }

    /**
     * 禁用管理员
     */
    public function del()
    {
        $ids = $this->request->request('ids');
        if (empty($ids)) $this->error_json('没有选择用户');

        AdminModel::destroy(['id'=>$ids]);
        $this->success_json('删除成功');
    }

    /**
     * 禁用管理员
     */
    public function stop()
    {
        $ids = $this->request->request('ids');
        if (empty($ids)) $this->error_json('没有选择用户');

        AdminModel::update(['status'=>0],['id'=>$ids]);
        $this->success_json('禁用成功');
    }

    /**
     * 启用管理员
     */
    public function start()
    {
        $ids = $this->request->request('ids');
        if (empty($ids)) $this->error_json('没有选择用户');

        AdminModel::update(['status'=>1],['id'=>$ids]);
        $this->success_json('启用成功');
    }

    /**
     * 系统规则列表
     */
    public function ruleList()
    {
        $rules = Rules::all();
        $list = [];
        foreach ($rules as $rule) {
            $list[$rule->name] = $rule;
        }
        $this->assign('row',$list);
        return $this->fetch();
    }

    /**
     * 修改系统规则
     */
    public function editRules()
    {
        $device_use_time = $this->request->request('device_use_time');
        $door_not_close_time = $this->request->request('door_not_close_time');
        $admin_op = $this->request->request('admin_op');
        if (empty($device_use_time) && empty($admin_op)) $this->error_json('规则不能设置为空');

        if (!empty($device_use_time)) {
            Rules::update(['value' => $device_use_time],['name'=>'device_use_time']);
        }
        if (!empty($door_not_close_time)) {
            Rules::update(['value' => $door_not_close_time],['name'=>'door_not_close_time']);
        }
        if (!empty($admin_op)) {
            Rules::update(['value' => $admin_op],['name'=>'only_administrator']);
        }
        $this->success_json('修改成功');
    }

    public function coverData()
    {
        return $this->fetch();
    }

    /**
     * 将读卡系统的用户数据向智能柜系统迁移！迁移后仅保留用户数据及设备基本信息。
     * 该操作会清空其他全部记录数据，需慎重操作！
     */
    public function card_to_door()
    {
        set_time_limit(0); // 取消脚本运行时间的超时上限

        // 格式化刷卡记录、设备使用记录、安检记录、异常记录
        $truncate_list = [
            'dp_admin_attachment',
            'dp_device',
            'dp_device_category',
            'dp_door',
            'dp_gear',
            'dp_gear_record',
            'dp_grade',
            'dp_iris',
            'dp_member_record',
            'dp_member_user',
            'dp_security_check_record',
            'dp_unusual_record',
            'dp_used_record',
        ];
        foreach ($truncate_list as $tcl_item) {
            db2($tcl_item,'db2')->execute("TRUNCATE TABLE $tcl_item");
        }

        // 拷贝设备分类表
        cover_table_to_db2('dp_device_category', 'id,name,image,createtime,updatetime,deletetime', 'db2');

        // 拷贝设备表
        cover_table_to_db2('dp_device', 'id,device_serial,device_name,device_model,scrap_time,warning_time,check_time,status,category_id', 'db2');

        // 拷贝班组表
        cover_table_to_db2('dp_grade', 'id,grade_name,leader,mobile', 'db2');

        // 拷贝用户表
        cover_table_to_db2('dp_member_user', 'id,user_serial,username,mobile,grade_id,position,entry_time,iris,reg_time,device_cate', 'db2');

        // 拷贝虹膜表
        cover_table_to_db2('dp_iris', 'id,iris_serial,port', 'db2');

        $this->success_json('数据迁移成功');
    }

    /**
     * 将智能柜系统的用户数据向读卡系统迁移！迁移后仅保留用户数据及设备基本信息。
     * 该操作会清空其他全部记录数据，需慎重操作！
     */
    public function door_to_card()
    {
        // 格式化表
        $truncate_list = [
            'dp_admin_attachment',
            'dp_device',
            'dp_device_category',
            'dp_device_usage_record',
            'dp_grade',
            'dp_iris',
            'dp_member_user',
            'dp_read_card_record',
            'dp_security_check_record',
            'dp_unusual_record',
        ];
        foreach ($truncate_list as $tcl_item) {
            db2($tcl_item,'db2')->execute("TRUNCATE TABLE $tcl_item");
        }

        // 拷贝设备分类表
        cover_table_to_db2('dp_device_category', 'id,name,image,createtime,updatetime,deletetime', 'db2');
        // 拷贝设备表
        cover_table_to_db2('dp_device', 'id,device_serial,device_name,device_model,scrap_time,warning_time,check_time,status,category_id', 'db2');
        // 拷贝班组表
        cover_table_to_db2('dp_grade', 'id,grade_name,leader,mobile', 'db2');
        // 拷贝用户表
        cover_table_to_db2('dp_member_user', 'id,user_serial,username,mobile,grade_id,position,entry_time,iris,reg_time,device_cate', 'db2');
        // 拷贝虹膜表
        cover_table_to_db2('dp_iris', 'id,iris_serial,port', 'db2');

        $this->success_json('数据迁移成功');
    }
}
